# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.

from odoo import fields, models, api, tools

import logging
_logger = logging.getLogger(__name__)



class Survey(models.Model):
    _inherit = "survey.survey"
    category = fields.Selection(selection_add=[('consult_consultation', 'Consultation')])


class ConsultSurvey(models.Model):
    # 某顾问专用的 咨询调研表
    _name = "consult.survey"
    _description = 'ConsultSurvey'
    _inherit = ['mail.thread']
    # _inherits = {'survey.survey':'survey_id'}
    _rec_name = 'consultee_type_id'
    # _order = "consultee_type_id"

    consultant_id = fields.Many2one( 'res.partner', 'Consultant' )
    consultee_type_id = fields.Many2one( 'consult.consultee.type'  )
    consultee_type_code = fields.Char(related='consultee_type_id.code', store=True)

    survey_id = fields.Many2one( 'survey.survey', "survey",
        domain=[('category', '=', 'consult_consultation')] )

    def name_get(self):
        result = []
        for rec in self:
            name = rec.consultant_id.name + ' ' + rec.consultee_type_id.name
            result.append((rec.id, name))
        return result


class Consultation(models.Model):
    # 咨询调研表答题
    _description = 'Consultation'
    _name = "consult.consultation"
    _inherit = ['mail.thread']
    # _order = "id"

    date = fields.Date(string='Date', default=fields.Datetime.now)

    state = fields.Selection([
        ('draft', 'Draft'),
        ('ready', 'Ready'),
        ('done', 'Locked'),
        ('cancel', 'Cancelled'),
        ], string='Status', readonly=True, copy=False, index=True, default='draft')

    sequence = fields.Integer(index=True, default=1)
    # name = fields.Char(index=True)
    partner_id = fields.Many2one('res.partner', 'Consultee')
    consult_survey_id = fields.Many2one('consult.survey', string="Consult Survey" )
    consultant_id = fields.Many2one(
        'res.partner', related='consult_survey_id.consultant_id', string="Consultant" )
    survey_id = fields.Many2one(
        'survey.survey', related='consult_survey_id.survey_id', string="Survey" )

    src_response_id = fields.Many2one('survey.user_input', "Response 1", ondelete="set null")
    response_id = fields.Many2one('survey.user_input', "Response", compute="_compute_response_id")

    @api.depends('partner_id','consult_survey_id')
    def _compute_response_id(self):
        for rec in self:
            if not rec.src_response_id:
                rec.set_response()
            rec.response_id = rec.src_response_id


    def name_get(self):
        result = []
        for rec in self:
            name = rec.consultant_id.name + ' ' + rec.partner_id.name + ' ' + str(rec.sequence)
            result.append((rec.id, name))
        return result

    def action_draft(self):
        return self.write({'state': 'draft'})

    def action_ready(self):
        return self.write({'state': 'ready'})

    def action_done(self):
        return self.write({'state': 'done'})

    def action_cancel(self):
        return self.write({'state': 'cancel'})

    def set_response(self):
        self.ensure_one()
        # question_type_to_answer_type = {
        #         'free_text': 'free_text',
        #         'textbox': 'text',
        #         'numerical_box': 'number',
        #         'date': 'date',
        #         'datetime': 'datetime',
        #         'simple_choice': 'suggestion',
        #         'multiple_choice': 'suggestion',
        #         'matrix': 'suggestion',
        # }

        survey = self.survey_id

        # user_input_line_ids_vals = [ 
        #         ( 0,0, {
        #             'question_id': q.id,
        #             'answer_type': question_type_to_answer_type.get(q.question_type)
        #         } )
        #         for q in survey.question_ids if q.question_type in [ 
        #             'free_text', 'textbox', 'date', 'datetime' ] ]

        question_ids = [ ( 4, q.id) for q in survey.question_ids  ]

        vals = {
                'survey_id': survey.id,
                'partner_id': self.partner_id.id,
                'question_ids' : question_ids,
                # 'user_input_line_ids': user_input_line_ids_vals
        }
            
        user_input = self.src_response_id.create(vals)
        self.src_response_id = user_input



    @api.model
    def create(self, values):
        consultation = super(Consultation, self).create(values)
        if not consultation.src_response_id:
            consultation.set_response()

        return consultation


    @api.model
    def _consultation_get(self, consultant_id, partner_id ):
        # after consultee login, 
        # get current consultation with his consultant

        domain = [
            ['partner_id','=', partner_id.id],
            ['consult_survey_id.consultant_id','=', consultant_id.id],
            ['state', 'in',['draft','ready']]
        ]

        consultation = self.search(domain, limit=1)
        if consultation:
            # if not consultation.src_response_id:
            #     consultation.set_response()

            return consultation

        domain2 = [
            ['consultant_id','=', consultant_id.id],
            ['consultee_type_id','=', partner_id.consultee_type_id.id],
        ]

        survey = self.env['consult.survey'].search(domain2, limit=1)

        vals = {
                'partner_id': partner_id.id,
                'consult_survey_id': survey.id
        }

        return self.create(vals)


